package com.qf.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.TlUser;
import com.qf.mapper.UserMapper;
import com.qf.service.UserService;
import com.qf.utils.Mycode;
import com.qf.utils.RedisKey;
import com.qf.utils.ResultMsg;
import com.qf.utils.TokenTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TlUser> implements UserService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    JavaMailSender javaMailSender;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public ResultMsg login(String userName, String userPass) {
        QueryWrapper<TlUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        wrapper.eq("user_pass", userPass);
        TlUser one = super.getOne(wrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.LOGIN_ERRO);

        String uuid = UUID.randomUUID().toString();
        String token = TokenTools.create(userName, userPass);
        redisTemplate.opsForValue().set(uuid, token);
        redisTemplate.boundValueOps(uuid).expire(30, TimeUnit.MINUTES);
        return ResultMsg.SUCCESS(uuid);
    }

    @Override//查询该登录用户的信息  个人信息查询
    public ResultMsg user(HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER +uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser one = super.getOne(queryWrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        return ResultMsg.SUCCESS(one);
    }

    @Override//注册VIP
    public ResultMsg registvip(HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser one = super.getOne(queryWrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        one.setUserVip(1);
        boolean b = super.saveOrUpdate(one);
        if (b)
            return ResultMsg.SUCCESS();
        return ResultMsg.ERROR(Mycode.REGISTER_ERRO);
    }

    @Override//注册
    public ResultMsg regist(TlUser user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", user.getUserName());
        TlUser nameuser = super.getOne(queryWrapper);
        if (nameuser != null)
            return ResultMsg.ERROR(Mycode.REGISTER_ERRO, "用户名已存在,请重新输入");
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_mail", user.getUserMail());
        TlUser mailuser = super.getOne(queryWrapper);
        if (mailuser != null)
            return ResultMsg.ERROR(Mycode.REGISTER_ERRO, "该邮箱已存在用户:" + mailuser.getUserName());
        Object o = redisTemplate.boundValueOps(user.getUserMail()).get();
        if (o == null && !(o instanceof String))
            throw new RuntimeException("验证码有误");
        String mail = (String) o;
        if (mail.equals(user.getCode())) {
            String encode = passwordEncoder.encode(user.getUserPass());
            user.setUserPass(encode);
            boolean b = super.saveOrUpdate(user);
            if (b) {
                redisTemplate.delete(user.getUserMail());
                return ResultMsg.SUCCESS();
            }
        }
        return ResultMsg.ERROR(Mycode.REGISTER_ERRO,"验证码有误");
    }

    @Override//修改手机号
    public ResultMsg updatetel(String tel, HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser one = super.getOne(queryWrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);


        one.setUserTel(tel);
        boolean b = super.saveOrUpdate(one);
        if (b)
            return ResultMsg.SUCCESS();
        return ResultMsg.ERROR(Mycode.UPDATE_ERRO);
    }

    @Override//修改密码
    public ResultMsg updatepass(String orderpass, String newuserpass, HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser one = super.getOne(queryWrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);

        if (orderpass.equals(audience.get(1))) {
            one.setUserPass(newuserpass);
            super.saveOrUpdate(one);
            return ResultMsg.SUCCESS();
        }
        return ResultMsg.ERROR(Mycode.ORDERPASS_ERRO, "原密码错误");
    }

    @Override//修改邮箱
    public ResultMsg updatemail(String mail, HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser one = super.getOne(queryWrapper);
        if (one == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);

        one.setUserMail(mail);
        boolean b = super.saveOrUpdate(one);
        if (b)
            return ResultMsg.SUCCESS();
        return ResultMsg.ERROR(Mycode.UPDATE_ERRO);
    }

    @Value("${spring.mail.username}")
    private String from;

    public ResultMsg usermail(String mail) {//发送验证码
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail);
        message.setSubject("注册验证码");
        String code = RandomUtil.randomString(4);
        message.setText(code);
        redisTemplate.boundValueOps(mail).set(code);
        redisTemplate.boundValueOps(mail).expire(2, TimeUnit.MINUTES);
        javaMailSender.send(message);
        return ResultMsg.SUCCESS();
    }

    @Override//退出登录
    public ResultMsg logout(String uuid) {
        redisTemplate.delete(RedisKey.LOGIN_USER+uuid);
        return ResultMsg.SUCCESS();
    }

    @Override//注销账户
    public ResultMsg deleteuser(String uuid) {
        String token = (String) redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        boolean remove = super.remove(queryWrapper);
        if (remove)
            return ResultMsg.SUCCESS();
        return ResultMsg.ERROR(Mycode.DELETEONE_ERRO);
    }

    @Override
    public ResultMsg modify(TlUser user) {
        TlUser byId = super.getById(user.getUserId());
        String newpass = user.getUserPass();
        if (!(byId.getUserPass().equals(newpass))) {
            String encode1 = passwordEncoder.encode(newpass);
                user.setUserPass(encode1);
            boolean b = super.saveOrUpdate(user);
            return ResultMsg.ERROR(666);
        }
        boolean b = super.saveOrUpdate(user);
        if (b) {
            return ResultMsg.SUCCESS();
        }
        else
            return ResultMsg.ERROR(202,"修改失败");
    }


}
